package com.eattravel.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.support.FormattingConversionServiceFactoryBean;
import org.springframework.stereotype.Component;


import javax.sound.sampled.spi.FormatConversionProvider;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.HashSet;
import java.util.Set;


/**
 * zx 2019.9.20
 *
 * 类型转换 可实现Stirng类型转换为Date类型
 */

@Component
public class StringToDataCoverter implements Converter<String,Date> {
    @Override
    public Date convert(String  s) {
        if(s==null){
            throw new RuntimeException("请输入数据");
        }
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        try{
            return df.parse(s);
        } catch (ParseException e) {
            throw new RuntimeException("输入类型格式不正确");
        }

    }



    // FormattingConversionServiceFactoryBean可以带格式化器@DateTimeFormat(pattern="yyyy-MM-dd")
    @Bean
    public ConversionServiceFactoryBean conversionServiceFactoryBean(){

        ConversionServiceFactoryBean conversionServiceFactoryBean=new ConversionServiceFactoryBean();
        Set<Converter> set=new HashSet<>();
        set.add(new StringToDataCoverter());
        conversionServiceFactoryBean.setConverters(set);
        return conversionServiceFactoryBean;
    }
}
